package io.renren.modules.basic.controller;




import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.utils.R;
import io.renren.modules.basic.entity.*;
import io.renren.modules.basic.service.*;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.work.Utils.ManageConstant;
import io.renren.modules.work.Utils.ManagePublicMethod;
import io.renren.modules.work.service.WorkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2019-10-14 10:50:42
 */
@Api(description = "任务接口")
@RestController
@RequestMapping(value = "generator/mtcctaskruninfo")
public class MtCcTaskRunInfoController extends AbstractController {
    @Autowired
    private MtCcTaskRunInfoService mtCcTaskRunInfoService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private MtCcTaskRunInfoLogService mtCcTaskRunInfoLogService;
    @Autowired
    private MtCcTaskRunInfoDetService mtCcTaskRunInfoDetService;
    @Autowired
    private MtCcTaskRunInfoDetLogService mtCcTaskRunInfoDetLogService;
    @Autowired
    private MtCcProductService mtCcProductService;
    @Autowired
    private MtCcWarehousPositionRelatService mtCcWarehousPositionRelatService;
    @Autowired
    private WorkService workService;

    /**
     * 列表
     */
    @ApiOperation(value = "任务列表",notes = "任务列表")
    @RequestMapping("/list")
    @RequiresPermissions("generator:mtcctaskruninfo:list")
    public R list(@RequestParam Map<String, Object> params){

        List<MtCcTaskRunInfoEntity> list = mtCcTaskRunInfoService.queryPage(params);

        return R.ok().put("list", list);
    }


    /**
     * 信息
     */
    @ApiOperation(value = "任务详情",notes = "任务详情")
    @RequestMapping("/info/{id}")
    @RequiresPermissions("generator:mtcctaskruninfo:info")
    public R info(@PathVariable("id") Integer id){
		MtCcTaskRunInfoEntity mtCcTaskRunInfo = mtCcTaskRunInfoService.getById(id);

        return R.ok().put("mtCcTaskRunInfo", mtCcTaskRunInfo);
    }

    /**
     * 保存
     * 参数：
     *      任务类型taskType
     *      产品id,型号，数量，单位
     */
    @ApiOperation(value = "新增任务",notes = "新增任务")
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("generator:mtcctaskruninfo:save")
    public R save(@RequestBody MtCcTaskRunInfoEntity mtCcTaskRunInfo){
        SysUserEntity user=this.getUser();
        String doorWay = sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_id", user.getUserId())).getDoorWay();
        if(mtCcTaskRunInfo.getTaskType()==0){
            MtCcProductEntity productEntity = mtCcProductService.getOne(new QueryWrapper<MtCcProductEntity>().eq("product_code", mtCcTaskRunInfo.getModel()));
            List<MtCcWarehousPositionRelatEntity> mtCcWarehousPositionRelats = mtCcWarehousPositionRelatService.list(new QueryWrapper<MtCcWarehousPositionRelatEntity>().eq("product_id", productEntity.getId()));
            int num=0;
            for (MtCcWarehousPositionRelatEntity mtCcWarehousPositionRelatEntity:mtCcWarehousPositionRelats) {
                num = num + mtCcWarehousPositionRelatEntity.getQuantity();
                if (num >= Integer.parseInt(mtCcTaskRunInfo.getNum())) {
                    break;
                }
            }
            if (num<Integer.parseInt(mtCcTaskRunInfo.getNum())){
                return R.error("仓库中"+productEntity.getProductName()+"数量为"+num+",你要出库的数量为"+mtCcTaskRunInfo.getNum()+",仓库数量不够出库！");
            }

            /**
             * 1.把手动下的主任务存到数据库中
             */
            mtCcTaskRunInfo.setCreateTime(new Date());
            mtCcTaskRunInfo.setUserId(Integer.parseInt(String.valueOf(user.getUserId())));
            mtCcTaskRunInfo.setUserName(user.getUsername());
            mtCcTaskRunInfo.setTaskType(0);
            mtCcTaskRunInfo.setStatus(0);
            mtCcTaskRunInfo.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.OUT_STOCK_ORDER_TYPE,doorWay));
            mtCcTaskRunInfo.setProductId(productEntity.getId());
            mtCcTaskRunInfo.setModel(productEntity.getProductCode());
            mtCcTaskRunInfo.setSource(user.getUsername());
            mtCcTaskRunInfoService.save(mtCcTaskRunInfo);
            mtCcTaskRunInfo.setOrderNum(mtCcTaskRunInfo.getId());
            mtCcTaskRunInfoService.updateById(mtCcTaskRunInfo);
            Map<String,Object> params=new HashMap();
            params.put("productId",productEntity.getId());
            params.put("checkOutNum",mtCcTaskRunInfo.getNum());
            params.put("doorWay",mtCcTaskRunInfo.getTaskCode().substring(1,3));
            params.put("id",mtCcTaskRunInfo.getId());
            workService.checkOutMainTaskForDet(params);

            /**
             * 2.把手动下的主任务的日志存到数据库
             */
            MtCcTaskRunInfoLogEntity mtCcTaskRunInfoLogEntity = new MtCcTaskRunInfoLogEntity();
            mtCcTaskRunInfoLogEntity.setCreateTime(new Date());
            mtCcTaskRunInfoLogEntity.setUserId(Integer.parseInt(String.valueOf(user.getUserId())));
            mtCcTaskRunInfoLogEntity.setUserName(user.getUsername());
            mtCcTaskRunInfoLogEntity.setTaskType(0);
            mtCcTaskRunInfoLogEntity.setStatus(0);
            mtCcTaskRunInfoLogEntity.setTaskCode(mtCcTaskRunInfo.getTaskCode());
            mtCcTaskRunInfoLogEntity.setProductId(productEntity.getId());
            mtCcTaskRunInfoLogEntity.setModel(productEntity.getProductCode());
            mtCcTaskRunInfoLogEntity.setNum(mtCcTaskRunInfo.getNum());
            mtCcTaskRunInfoLogEntity.setUnit(mtCcTaskRunInfo.getUnit());
            mtCcTaskRunInfoLogService.save(mtCcTaskRunInfoLogEntity);

        }else if (mtCcTaskRunInfo.getTaskType()==1){
            mtCcTaskRunInfo.setTaskCode(ManagePublicMethod.creatOrderCode(ManageConstant.IN_STOCK_ORDER_TYPE,doorWay));
            mtCcTaskRunInfo.setCreateTime(new Date());
            mtCcTaskRunInfo.setUserId(Integer.parseInt(String.valueOf(user.getUserId())));
            mtCcTaskRunInfo.setUserName(user.getUsername());
            mtCcTaskRunInfo.setSource(user.getUsername());
            mtCcTaskRunInfo.setStatus(0);
            mtCcTaskRunInfoService.save(mtCcTaskRunInfo);
            mtCcTaskRunInfo.setOrderNum(mtCcTaskRunInfo.getId());
            mtCcTaskRunInfoService.updateById(mtCcTaskRunInfo);
        }


		//添加日志
        MtCcTaskRunInfoLogEntity mtCcTaskRunInfoLogEntity=new MtCcTaskRunInfoLogEntity();
        mtCcTaskRunInfoLogEntity.setCreateTime(mtCcTaskRunInfo.getCreateTime());
        mtCcTaskRunInfoLogEntity.setUserId(mtCcTaskRunInfo.getUserId());
        mtCcTaskRunInfoLogEntity.setUserName(mtCcTaskRunInfo.getUserName());
        mtCcTaskRunInfoLogEntity.setTaskType(mtCcTaskRunInfo.getTaskType());
        mtCcTaskRunInfoLogEntity.setTaskCode(mtCcTaskRunInfo.getTaskCode());
        mtCcTaskRunInfoLogEntity.setProductId(mtCcTaskRunInfo.getProductId());
        mtCcTaskRunInfoLogEntity.setModel(mtCcTaskRunInfo.getModel());
        mtCcTaskRunInfoLogEntity.setNum(mtCcTaskRunInfo.getNum());
        mtCcTaskRunInfoLogEntity.setUnit(mtCcTaskRunInfo.getUnit());
        mtCcTaskRunInfoLogEntity.setRemarks(mtCcTaskRunInfo.getRemarks());
        mtCcTaskRunInfoLogService.save(mtCcTaskRunInfoLogEntity);
        return R.ok();

    }

    /**
     * 修改
     */
    @ApiOperation(value = "修改任务",notes = "修改任务")
    @RequestMapping("/update")
    @RequiresPermissions("generator:mtcctaskruninfo:update")
    public R update(@RequestBody MtCcTaskRunInfoEntity mtCcTaskRunInfo){
        mtCcTaskRunInfo.setUpdateTime(new Date());
		mtCcTaskRunInfoService.updateById(mtCcTaskRunInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除任务",notes = "删除任务")
    @RequestMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("generator:mtcctaskruninfo:delete")
    public R delete(@RequestBody Integer id){
        MtCcTaskRunInfoEntity mtCcTaskRunInfo = mtCcTaskRunInfoService.getById(id);
        MtCcTaskRunInfoLogEntity mtCcTaskRunInfoLog = mtCcTaskRunInfoLogService
                .getOne(new QueryWrapper<MtCcTaskRunInfoLogEntity>()
                        .eq("task_code", mtCcTaskRunInfo.getTaskCode()));
        //修改日志，状态改为3-取消执行
        mtCcTaskRunInfoLog.setStatus(3);
        mtCcTaskRunInfoLogService.updateById(mtCcTaskRunInfoLog);
        List<MtCcTaskRunInfoDetEntity> mtCcTaskRunInfoDetEntities = mtCcTaskRunInfoDetService
                .list(new QueryWrapper<MtCcTaskRunInfoDetEntity>().eq("task_run_id", id));
        if (mtCcTaskRunInfoDetEntities.size()!=0){
            List ids=new ArrayList();
            for (int i=0;i<mtCcTaskRunInfoDetEntities.size();i++){
                ids.add(mtCcTaskRunInfoDetEntities.get(i).getId());
            }
            mtCcTaskRunInfoDetService.removeByIds(ids);
        }//删除对应主任务下的子任务
        List<MtCcTaskRunInfoDetLogEntity> mtCcTaskRunInfoLogDetEntitis = mtCcTaskRunInfoDetLogService
                .list(new QueryWrapper<MtCcTaskRunInfoDetLogEntity>().eq("task_run_id", id));
        if (mtCcTaskRunInfoLogDetEntitis.size()!=0){
            for (int i=0;i<mtCcTaskRunInfoDetEntities.size();i++){
                MtCcTaskRunInfoDetLogEntity mtCcTaskRunInfoDetLogEntity = mtCcTaskRunInfoLogDetEntitis.get(i);
                mtCcTaskRunInfoDetLogEntity.setStatus(3);
                mtCcTaskRunInfoDetLogService.updateById(mtCcTaskRunInfoDetLogEntity);
            }
        }//修改子任务日志表中的对应子任务状态为取消执行
        mtCcTaskRunInfoService.removeById(id);

        return R.ok();
    }

    /**
     * 排序
     */
    @ApiOperation(value = "排序任务",notes = "排序任务")
    @PostMapping("/sort")
    public R sort(@RequestBody List<MtCcTaskRunInfoEntity> mtCcTaskRunInfoEntities){
        mtCcTaskRunInfoService.saveOrUpdateBatch(mtCcTaskRunInfoEntities);
        //List<MtCcTaskRunInfoEntity> list = mtCcTaskRunInfoService.list(new QueryWrapper<MtCcTaskRunInfoEntity>().orderBy(false, false, "order_num"));
        return R.ok();
    }
}
